/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 12/09/2009, 12:23:44 PM
 */
package scms;

import javax.swing.*;
import javax.swing.table.*;
import java.util.LinkedList;
import java.io.*;

/**
 * gui scms class
 * @author pumped
 */
public class ScmsGuiMenu extends javax.swing.JFrame {

	DefaultTableModel productsTable = new DefaultTableModel();
	DefaultTableModel inventoryTable = new DefaultTableModel();
	DefaultTableModel ordersTable = new DefaultTableModel();
	DefaultTableModel partsTable = new DefaultTableModel();
	private Inventory inventory;

	/**
	 * default constructor
	 */
	public ScmsGuiMenu() {
		initComponents();

		productsTable.addColumn("ID");
		productsTable.addColumn("Name");
		productsTable.addColumn("Description");
		productsTable.addColumn("Stock");

		inventoryTable.addColumn("ID");
		inventoryTable.addColumn("Name");
		inventoryTable.addColumn("Description");
		inventoryTable.addColumn("Quality");
		inventoryTable.addColumn("Quantity");

		ordersTable.addColumn("ID");
		ordersTable.addColumn("Name");
		ordersTable.addColumn("Quantity");

		partsTable.addColumn("ID");
		partsTable.addColumn("Name");
		partsTable.addColumn("Quantity");
		partsTable.addColumn("Quality");

		tblProducts.setModel(productsTable);
		tblInventory.setModel(inventoryTable);
		tblOrders.setModel(ordersTable);
		tblParts.setModel(partsTable);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlOrders = new javax.swing.JTabbedPane();
        pnlProducts = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProducts = new javax.swing.JTable();
        pnlInventory = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblInventory = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblOrders = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tblParts = new javax.swing.JTable();
        btnView = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnOrder = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnuFile = new javax.swing.JMenu();
        mnuImport = new javax.swing.JMenuItem();
        mnuExport = new javax.swing.JMenuItem();
        asdf = new javax.swing.JSeparator();
        mnuChatClient = new javax.swing.JMenuItem();
        mnuChatServer = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        mnuExit = new javax.swing.JMenuItem();
        mnuProducts = new javax.swing.JMenu();
        mnuNewInventoryItem = new javax.swing.JMenuItem();
        mnuNewProduct = new javax.swing.JMenuItem();
        mnuEditProduct = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SCMS");

        pnlOrders.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                pnlOrdersStateChanged(evt);
            }
        });

        tblProducts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {new Integer(1), "Case", "A Regular computer case"},
                {new Integer(2), "Motherboard", "A Standard Atx motherboard"}
            },
            new String [] {
                "ID", "Product", "Description"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblProducts.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblProducts);

        javax.swing.GroupLayout pnlProductsLayout = new javax.swing.GroupLayout(pnlProducts);
        pnlProducts.setLayout(pnlProductsLayout);
        pnlProductsLayout.setHorizontalGroup(
            pnlProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
        );
        pnlProductsLayout.setVerticalGroup(
            pnlProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
        );

        pnlOrders.addTab("Products", pnlProducts);

        tblInventory.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tblInventory);

        javax.swing.GroupLayout pnlInventoryLayout = new javax.swing.GroupLayout(pnlInventory);
        pnlInventory.setLayout(pnlInventoryLayout);
        pnlInventoryLayout.setHorizontalGroup(
            pnlInventoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
        );
        pnlInventoryLayout.setVerticalGroup(
            pnlInventoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
        );

        pnlOrders.addTab("Inventory", pnlInventory);

        tblOrders.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(tblOrders);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
        );

        pnlOrders.addTab("Orders", jPanel1);

        tblParts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane4.setViewportView(tblParts);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
        );

        pnlOrders.addTab("Parts List", jPanel2);

        btnView.setText("View");
        btnView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewActionPerformed(evt);
            }
        });

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnOrder.setText("Order");
        btnOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOrderActionPerformed(evt);
            }
        });

        mnuFile.setText("File");

        mnuImport.setText("Import");
        mnuImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuImportActionPerformed(evt);
            }
        });
        mnuFile.add(mnuImport);

        mnuExport.setText("Export");
        mnuExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuExportActionPerformed(evt);
            }
        });
        mnuFile.add(mnuExport);
        mnuFile.add(asdf);

        mnuChatClient.setText("Chat (Client)");
        mnuChatClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuChatClientActionPerformed(evt);
            }
        });
        mnuFile.add(mnuChatClient);

        mnuChatServer.setText("Chat (Server)");
        mnuChatServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuChatServerActionPerformed(evt);
            }
        });
        mnuFile.add(mnuChatServer);
        mnuFile.add(jSeparator1);

        mnuExit.setText("Exit");
        mnuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuExitActionPerformed(evt);
            }
        });
        mnuFile.add(mnuExit);

        jMenuBar1.add(mnuFile);

        mnuProducts.setText("Products/Inventory");

        mnuNewInventoryItem.setText("New Product/Inventory Item");
        mnuNewInventoryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuNewInventoryItemActionPerformed(evt);
            }
        });
        mnuProducts.add(mnuNewInventoryItem);

        mnuNewProduct.setText("New Product from Inventory");
        mnuNewProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuNewProductActionPerformed(evt);
            }
        });
        mnuProducts.add(mnuNewProduct);

        mnuEditProduct.setText("Edit Selected");
        mnuProducts.add(mnuEditProduct);

        jMenuBar1.add(mnuProducts);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlOrders, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 631, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(482, Short.MAX_VALUE)
                .addComponent(btnEdit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnView)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnOrder)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlOrders, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEdit)
                    .addComponent(btnView)
                    .addComponent(btnOrder))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	/**
	 * menu item new inventory item action
	 * @param evt
	 */
	private void mnuNewInventoryItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewInventoryItemActionPerformed
		AddItem addInvItem = new AddItem(this, inventory);
		addInvItem.showWindow(true);

		//TODO listen to the window

	}//GEN-LAST:event_mnuNewInventoryItemActionPerformed

	/**
	 * view button action
	 * @param evt
	 */
	private void btnViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewActionPerformed
		openEdit(false);
	}//GEN-LAST:event_btnViewActionPerformed

	/**
	 * import from xml menu action
	 * @param evt
	 */
	private void mnuImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuImportActionPerformed
		inventory.importItems();
		inventory.importProducts();
		updateProducts();
		updateInventory();
		updateOrders();
		updateParts();
	}//GEN-LAST:event_mnuImportActionPerformed

	/**
	 * edit button action
	 * @param evt
	 */
	private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
		openEdit(true);
	}//GEN-LAST:event_btnEditActionPerformed

	/**
	 * panel tab changed
	 * @param evt
	 */
	private void pnlOrdersStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pnlOrdersStateChanged
		switch (pnlOrders.getSelectedIndex()) {
			case 0:
				btnOrder.setEnabled(true);
				break;
			case 1:
				btnOrder.setEnabled(false);
				break;
			case 2:
				btnOrder.setEnabled(false);
				break;
		}
	}//GEN-LAST:event_pnlOrdersStateChanged

	/**
	 * export xml
	 * @param evt
	 */
	private void mnuExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuExportActionPerformed
		inventory.export();
	}//GEN-LAST:event_mnuExportActionPerformed

	/**
	 * new product menu action
	 * @param evt
	 */
	private void mnuNewProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewProductActionPerformed
		if (pnlOrders.getSelectedIndex() == 1) {
			int id = Integer.parseInt(tblInventory.getValueAt(tblInventory.getSelectedRow(), 0).toString());
			Product newProduct = new Product();
			newProduct.setID(inventory.nextProductID());
			newProduct.setItem(inventory.getItemByID(id));

			inventory.getProducts().add(newProduct);
			updateProducts();
			updateOrders();
		}
	}//GEN-LAST:event_mnuNewProductActionPerformed

	/**
	 * order button action
	 * @param evt
	 */
	private void btnOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrderActionPerformed
		int id = Integer.parseInt(tblProducts.getValueAt(tblProducts.getSelectedRow(), 0).toString());
		Product product = inventory.getProductByID(id);
		if (product.getBackOrder() == 0) {
			product.setBackOrder(1);
		}
		System.out.println("lol");
		OrderGui order = new OrderGui(this, id, inventory);
		order.showWindow(true);
	}//GEN-LAST:event_btnOrderActionPerformed

	/**
	 * menu exit button action
	 * @param evt
	 */
	private void mnuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuExitActionPerformed
		this.dispose();
	}//GEN-LAST:event_mnuExitActionPerformed

	/**
	 * menu chat server action
	 * @param evt
	 */
	private void mnuChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuChatServerActionPerformed
		//start chat gui client with localhost
		ChatGui chat = new ChatGui(this, "localhost");
		chat.setVisible(true);
	}//GEN-LAST:event_mnuChatServerActionPerformed

	/**
	 * menu chat client action
	 * @param evt
	 */
	private void mnuChatClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuChatClientActionPerformed
		//start chat gui
		ChatGui chat = new ChatGui(this);
		chat.setVisible(true);
	}//GEN-LAST:event_mnuChatClientActionPerformed

	/**
	 * function opens view or edit windows
	 * @param button
	 */
	private void openEdit(boolean button) {
		int id;

		//get selected item
		switch (pnlOrders.getSelectedIndex()) {
			case 0:
				try {
					id = Integer.parseInt(tblProducts.getValueAt(tblProducts.getSelectedRow(), 0).toString());
					AddItem addInvItem = new AddItem(this, inventory, button, id, false);
					addInvItem.showWindow(true);
				} catch (Exception ex) {
					System.out.println("Debug: No selected product");
					return;
				}
				break;
			case 1:
				try {
					id = Integer.parseInt(tblInventory.getValueAt(tblInventory.getSelectedRow(), 0).toString());

				} catch (Exception ex) {
					System.out.println("Debug: No selected inventory");
					return;
				}
				AddItem addInvItem = new AddItem(this, inventory, button, id, true);
				addInvItem.showWindow(true);
				break;

			case 2:
				try {
					id = Integer.parseInt(tblOrders.getValueAt(tblOrders.getSelectedRow(), 0).toString());

				} catch (Exception ex) {
					System.out.println("Debug: No selected inventory");
					return;
				}
				OrderGui order = new OrderGui(this, id, inventory);
				order.showWindow(true);
				break;
		}
	}
	/**
	 * @param args the command line arguments
	 */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSeparator asdf;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnOrder;
    private javax.swing.JButton btnView;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuItem mnuChatClient;
    private javax.swing.JMenuItem mnuChatServer;
    private javax.swing.JMenuItem mnuEditProduct;
    private javax.swing.JMenuItem mnuExit;
    private javax.swing.JMenuItem mnuExport;
    private javax.swing.JMenu mnuFile;
    private javax.swing.JMenuItem mnuImport;
    private javax.swing.JMenuItem mnuNewInventoryItem;
    private javax.swing.JMenuItem mnuNewProduct;
    private javax.swing.JMenu mnuProducts;
    private javax.swing.JPanel pnlInventory;
    private javax.swing.JTabbedPane pnlOrders;
    private javax.swing.JPanel pnlProducts;
    private javax.swing.JTable tblInventory;
    private javax.swing.JTable tblOrders;
    private javax.swing.JTable tblParts;
    private javax.swing.JTable tblProducts;
    // End of variables declaration//GEN-END:variables

	/**
	 * function shows window
	 * @param opt
	 */
	public void showWindow(boolean opt) {
		this.setVisible(opt);
	}

	/**
	 * sets current inventory
	 * @param inventory
	 */
	public void setInventory(Inventory inventory) {
		this.inventory = inventory;
		updateInventory();
		updateProducts();
		updateOrders();
		updateParts();
	}

	/**
	 * update products table
	 */
	public void updateProducts() {
		int rows = productsTable.getRowCount();
		for (int i = 0; i < rows; i++) {
			productsTable.removeRow(0);
		}

		for (Product p : inventory.getProducts()) {
			productsTable.addRow(new Object[]{p.getID(), p.getItem().getName(), p.getItem().getDescription(), p.getItem().getQuantity()});
		}
	}

	/**
	 * updates inventory table
	 */
	public void updateInventory() {
		int rows = inventoryTable.getRowCount();
		for (int i = 0; i < rows; i++) {
			inventoryTable.removeRow(0);
		}

		for (InventoryItem i : inventory.getInventory()) {
			inventoryTable.addRow(new Object[]{i.getID(), i.getName(), i.getDescription(), i.getQuality(), i.getQuantity()});
		}
	}

	/**
	 * updates order table
	 */
	public void updateOrders() {
		int rows = ordersTable.getRowCount();
		for (int i = 0; i < rows; i++) {
			ordersTable.removeRow(0);
		}

		for (Product p : inventory.getProducts()) {
			if (p.getBackOrder() > 0) {
				ordersTable.addRow(new Object[]{p.getID(), p.getItem().getName(), p.getBackOrder()});
			}
		}
	}

	/**
	 * updates parts list
	 */
	public void updateParts() {
		partsTable.addRow(new Object[]{1, 1, 1, 1});
		int rows = partsTable.getRowCount();
		for (int i = 0; i < rows; i++) {
			partsTable.removeRow(0);
		}
		boolean exit = false;
		int row = -1;

		for (Product p : inventory.getProducts()) {
			if (p.getBackOrder() > 0) {
				System.out.println(p.getItem().getName());
				//for each part
				for (Part i : p.getItem().getParts()) {
					System.out.println(p.getItem().getName() + ": " + i.item.getName());
					exit = false;
					row = -1;
					//check if part already exists
					for (int j = 0; j < partsTable.getRowCount() && exit == false; j++) {
						if (Integer.parseInt(partsTable.getValueAt(j, 0).toString()) == i.item.getID()) {
							row = j;
							exit = true;
						}
					}
					if (row >= 0) {
						//increment it
						int value = Integer.parseInt(partsTable.getValueAt(row, 2).toString());
						partsTable.setValueAt(value + (p.getBackOrder() * i.amount), row, 2);
						exit = true;
					} else {
						partsTable.addRow(new Object[]{i.item.getID(), i.item.getName(), p.getBackOrder() * i.amount, i.item.getQuality()});
					}

					//else
					//add it
				}
			}
		}
	}
}
